package org.ielse.frame.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;

import org.ielse.frame.App;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class BaseUtil {

    public static Map<String, String> initMap(Object... params) {
        if (params == null || params.length < 1 || params.length % 2 != 0) return null;
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < params.length; i = i + 2) {
            map.put(String.valueOf(params[i]), String.valueOf(params[i + 1]));
        }
        return map;
    }

    public static Bundle initBundle(Object... params) {
        if (params == null || params.length < 1 || params.length % 2 != 0) return null;
        Bundle bundle = new Bundle();
        for (int i = 0; i < params.length; i = i + 2) {
            if (params[i + 1] instanceof String) {
                bundle.putString(String.valueOf(params[i]), String.valueOf(params[i + 1]));
            } else if (params[i + 1] instanceof Integer) {
                bundle.putInt(String.valueOf(params[i]), Integer.valueOf(params[i + 1].toString()));
            } else if (params[i + 1] instanceof Float) {
                bundle.putFloat(String.valueOf(params[i]), Float.valueOf(params[i + 1].toString()));
            } else if (params[i + 1] instanceof Double) {
                bundle.putDouble(String.valueOf(params[i]), Double.valueOf(params[i + 1].toString()));
            } else if (params[i + 1] instanceof Long) {
                bundle.putLong(String.valueOf(params[i]), Long.valueOf(params[i + 1].toString()));
            } else if (params[i + 1] instanceof Short) {
                bundle.putShort(String.valueOf(params[i]), Short.valueOf(params[i + 1].toString()));
            } else if (params[i + 1] instanceof Byte) {
                bundle.putByte(String.valueOf(params[i]), Byte.valueOf(params[i + 1].toString()));
            } else if (params[i + 1] instanceof Boolean) {
                bundle.putBoolean(String.valueOf(params[i]), Boolean.valueOf(params[i + 1].toString()));
            } else {
                throw new IllegalArgumentException("param should be base type");
            }
        }
        return bundle;
    }

    public static String inputStreamToString(InputStream in) {
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String result = null;
        try {
            br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append("\n").append(line);
            }
            if (sb.length() > 0) result = sb.substring("\n".length());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static boolean inputStreamToOutputStream(InputStream input, OutputStream output) {
        BufferedInputStream in = new BufferedInputStream(input, 8 * 1024);
        BufferedOutputStream out = new BufferedOutputStream(output, 8 * 1024);
        try {
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) out.close();
                if (in != null) in.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static InputStream bitmapToInputStream(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray()));
    }

    public static InputStream byteToInputStream(byte[] bytes) {
        return new BufferedInputStream(new ByteArrayInputStream(bytes));
    }

    public static Drawable bitmapToDrawable(Resources res, Bitmap bitmap) {
        return new BitmapDrawable(res, bitmap);
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    public static int dipToPx(int value) {
        DisplayMetrics dm = App.i().getResources().getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm);
    }

    public static int spToPx(int value) {
        DisplayMetrics dm = App.i().getResources().getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, dm);
    }


    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }


    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }


    public static int getStatusBarHeight(Context context) {

        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }


    public static Bitmap screenShotWithStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bp;

    }

    public static Bitmap screenShotWithoutStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return bp;
    }


    public static boolean isScreenVertical(Activity context) {
        if (context == null) return true;
        int rotation = context.getWindowManager().getDefaultDisplay()
                .getRotation();
        switch (rotation) {
            case Surface.ROTATION_90:
            case Surface.ROTATION_270:
                return false;
        }
        return true;
    }
}
